import React from 'react';
import { messages } from 'share/common';
import Chooser from 'components/chooser';
import { Col, Row, Checkbox } from 'antd';
import WrapFormItem from 'components/wrap-form-item';

const hasValue = value => value && value.department && value.department.length > 0;

const onChangeDepartment = (value, department, onChange) => {
  if (!department || !department[0]) {
    value.isIncludeChildren = false;
  }
  if( value.isIncludeChildren === void 0){
    value.isIncludeChildren = true;
  }
  value.department = department;
  onChange(value);
};

const onChangeCheckbox = (value, checked, onChange) => {
  value.isIncludeChildren = checked;
  onChange(value);
};

export default {
  id: 'department',
  label: messages('common.department')/*部门*/,
  component: <WrapFormItem parser={value => value || {}}>
    {(onChange, value) => (
      <Row gutter={10}>
        <Col span={13}>
          <Chooser
            type='department'
            labelKey='name'
            valueKey='departmentCode'
            value={value.department}
            listExtraParams={{status: '1002'}}
            onChange={(department) => onChangeDepartment(value, department, onChange)}
          />

        </Col>
        <Col span={10} offset={1} className="null-batch-num">
          <Checkbox
            disabled={!value.department || !value.department[0]}
            checked={value.isIncludeChildren}
            onChange={e => onChangeCheckbox(value, e.target.checked, onChange)}
          />
          &nbsp;{messages('expense-14.key268')/*包含子部门*/}
        </Col>
      </Row>
    )}
  </WrapFormItem>,
  hasValue,
  parser: value => hasValue(value) ? {
    department: value.department.map(item => item.departmentCode),
    isIncludeChildren: value.isIncludeChildren
  } : null,
  tagParser: value => `${value.department.map(item => item.name)
    .join(',')} (${value.isIncludeChildren ? messages('expense-14.key268')/*包含子部门*/ : messages('expense-14.key269')/*不包含子部门*/})`
};
